package com.hndfsj.common.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.hndfsj.common.domain.TokenModel;
import com.hndfsj.common.service.ITokenService;
import com.hndfsj.framework.utils.RedisUtil;
import com.hndfsj.framework.utils.UUIDGenerator;
import com.hndfsj.framework.utils.properties.PropertiesUtil;

/**
 * 通过RedisUtil存储和验证token的实现类
 * 
 * @see com.hndfsj.common.service.TokenServiceImpl.authorization.manager.TokenManager
 * @author ScienJus
 * @date 2015/7/31.
 */
@Service("tokenService")
public class TokenServiceImpl implements ITokenService {

	public TokenModel createToken(String userName) {
		// 使用uuid作为源token
		String token = UUIDGenerator.UUIDValue();
		TokenModel model = new TokenModel(token, userName);
		// 存储到RedisUtil并设置过期时间
		RedisUtil.getJedis().set(token, userName);
		RedisUtil.getJedis().expire(token,
				Integer.parseInt(PropertiesUtil.getString(PropertiesUtil.redis, "redis-token-expiry-time")));
		return model;
	}

	public TokenModel getToken(String token) {
		String username = RedisUtil.getJedis().get(token);
		if (StringUtils.isNotBlank(username)) {
			TokenModel model = new TokenModel(username);
			RedisUtil.getJedis().del(token);
			return model;
		}
		return null;
	}

	public TokenModel checkToken(String token) {
		TokenModel model = new TokenModel(RedisUtil.getJedis().get(token));
		RedisUtil.getJedis().del(token);
		return model;
	}
}
